<meta charset="UTF-8">
<div class="pd-10 system" id="device-type-wraper">
    <div style="padding: 5px 0">
        <i-button icon="md-add" @click="openAddDeviceTypeModal">添加设备类型</i-button>
    </div>
    <div>
        <i-table :columns="columns" :data="tableData" :loading="loading"></i-table>
    </div>

    <!-- 添加车辆类型 -->
    <Modal v-model="addDevTypeModal" width="520" class-name="vertical-center-modal">
        <p slot="header" style="color:#2D8CF0;text-align:center">
            <Icon type="md-add"></Icon>
            <span v-show="!isEdit">添加设备类型</span>
            <span v-show="isEdit">编辑设备类型</span>
        </p>
        <div>
            <Row>
                <i-col :span="3" :offset="1" style="height: 100%;text-align:right;line-height:32px;">
                    类型名称&nbsp;:&nbsp;
                </i-col>
                <i-col :span="7">
                    <i-input v-model.trim="devTypeInfo.typename"></i-input>
                </i-col>
                <i-col :span="3" :offset="2" style="height: 100%;text-align:right;line-height:32px;">
                    通信协议&nbsp;:&nbsp;
                </i-col>
                <i-col :span="7" v-show="!isEdit">
                    <i-select v-model="deviceCode">
                        <i-option v-for="item in deviceTypeList" :value="item.value" :key="item.value">{{ item.label }}</i-option>
                    </i-select>
                </i-col>
                <i-col :span="7" v-show="isEdit">
                    <i-input v-model.trim="devTypeInfo.typecode" :disabled="isEdit"></i-input>
                </i-col>
            </Row>
            <Row style="margin:10px 0;">
                <i-col span="3" :offset="1" style="height: 100%;text-align:right;line-height:32px;">序号长度: &nbsp;</i-col>
                <i-col span="7">
                    <input-number v-model.number="defaultidlength" :max="30" :min="8" style="width: 100%;"></input-number>
                </i-col>
            </Row>
            <Row style="margin:10px 0;">
                <i-col :span="3" :offset="1" style="height: 100%;line-height:32px;">
                    功能列表&nbsp;:&nbsp;
                </i-col>
                <i-col :span="20" style="height: 100%;line-height:32px;">
                    <checkbox-group v-model="functionsCheck">
                        <Checkbox v-for="item in functionsDesc" :label="item.mask">
                            <span>{{item.functionname}}</span>
                        </Checkbox>
                    </checkbox-group>
                </i-col>
            </Row>
            <Row>
                <i-col :span="4" style="height: 100%;text-align:right;line-height:32px;">
                    备注(中文)&nbsp;:&nbsp;
                </i-col>
                <i-col :span="19">
                    <i-input v-model.trim="remark" :autosize="{minRows:3}" type="textarea"></i-input>
                </i-col>
            </Row>
            <Row style="margin-top: 10px;">
                <i-col :span="4" style="height: 100%;text-align:right;line-height:32px;">
                    备注(英文)&nbsp;:&nbsp;
                </i-col>
                <i-col :span="19">
                    <i-input v-model.trim="remarken" :autosize="{minRows:3}" type="textarea"></i-input>
                </i-col>
            </Row>
        </div>
        <div slot="footer">
            <i-button type="primary" @click="handleAddDevType" style="width: 100%">{{isEdit?'编辑':'添加'}}</i-button>
        </div>
    </Modal>

    <Modal v-model="cmdModal" width="600" class-name="vertical-center-modal" fullscreen="false">
        <p slot="header" style="color:#f60;text-align:center">
            <Icon type="information-circled"></Icon>
            <span>选择设备指令</span>
        </p>
        <div>
            <Row style="margin: 10px 0" v-for="(item,index) in cmdList" :key="index">
                <i-col span="8" v-for="(type , index) in item" :key="type.cmdcode">
                    <Checkbox v-model="checkboxCmdObj[type.cmdcode]">{{type.cmdname}}</Checkbox>
                </i-col>
            </Row>
        </div>
        <div slot="footer">
            <i-button type="primary" @click="addInstructionsToDeviceTypes" style="width: 100%">确定</i-button>
        </div>
    </Modal>

    <script>
        vueInstanse = new Vue({
            el: "#device-type-wraper",
            data: function() {
                var me = this;
                return {
                    devTypeInfo: {
                        "typecode": null,
                        "typename": null,
                    },
                    functionsCheck: [],
                    remark: "",
                    remarken: "",
                    defaultidlength: 11,
                    deviceTypeList: [],
                    deviceCode: "",
                    isEdit: false,
                    addDevTypeModal: false,
                    cmdModal: false,
                    rowIndex: null,
                    oldtypename: null,
                    columns: [

                        {
                            title: '类型名称',
                            key: 'typename'
                        }, {
                            title: '通信协议',
                            key: 'typecode'
                        }, {
                            title: '序号长度',
                            key: 'defaultidlength'
                        }, {
                            title: '备注(中文)',
                            key: 'remark'
                        }, {
                            title: '备注(英文)',
                            key: 'remarken'
                        }, {
                            title: '操作',
                            key: 'action',
                            width: 250,
                            render: function(h, params) {
                                return h('div', [
                                    h('Button', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            marginRight: '5px'
                                        },
                                        on: {
                                            click: function() {
                                                me.openEditDevTypeModal(params);
                                            }
                                        }
                                    }, '修改'),
                                    h('Poptip', {
                                        props: {
                                            confirm: true,
                                            title: '确定要删除吗?'
                                        },
                                        on: {
                                            'on-ok': function() {
                                                me.handleDel(params);
                                            }
                                        }
                                    }, [
                                        h('Button', {
                                            props: {
                                                type: 'error',
                                                size: 'small'
                                            }
                                        }, "删除")
                                    ])
                                ]);
                            }
                        }
                    ],
                    tableData: [],
                    cmdList: [],
                    checkboxCmdObj: {},
                    loading: false,
                    cmdRecords: [],
                    functionsDesc: [],
                }
            },
            methods: {
                openAddDeviceTypeModal: function() {
                    this.isEdit = false;
                    this.addDevTypeModal = true;
                },
                handleDel: function(params) {
                    var me = this;
                    var url = myUrls.deleteDeviceType();
                    var data = {
                        devicetypeid: params.row.devicetypeid
                    };
                    utils.sendAjax(url, data, function(resp) {
                        if (resp.status == 0) {
                            me.$delete(me.tableData, params.index);
                            me.delDevTypeModal = false;
                            me.$Message.success("删除成功");
                        } else {
                            me.$Message.success("删除失败");
                        };
                    });
                },
                handleAddDevType: function() {
                    var me = this;
                    var url = null;
                    var data = null;
                    var lock = true;
                    if (this.isEdit) {
                        url = myUrls.editDeviceType();
                        data = {
                            "devicetypeid": this.devTypeInfo.devicetypeid,
                            "typecode": this.devTypeInfo.typecode,
                            "newtypename": this.devTypeInfo.typename,
                            "oldtypename": this.oldtypename,
                            "defaultidlength": this.defaultidlength,
                            'functionslong': this.getFunctionsLong(),
                        }
                    } else {
                        url = myUrls.addDeviceType();
                        data = {
                            "typecode": this.deviceCode,
                            "typename": this.devTypeInfo.typename,
                            "defaultidlength": this.defaultidlength,
                            'functionslong': this.getFunctionsLong(),
                        };
                    }

                    for (var key in data) {
                        if (data.hasOwnProperty(key)) {
                            if (data[key] == undefined) {
                                lock = false;
                            }
                        }
                    };
                    if (!lock) {
                        this.$Message.error("参数都是必填的");
                        return;
                    }


                    if (this.remark !== "") {
                        data.remark = this.remark;
                    }
                    if (this.remarken !== "") {
                        data.remarken = this.remarken;
                    }
                    utils.sendAjax(url, data, function(resp) {
                        if (resp.status == 0) {
                            if (me.isEdit) {
                                for (var key in me.devTypeInfo) {
                                    if (me.devTypeInfo.hasOwnProperty(key)) {
                                        var val = me.devTypeInfo[key];
                                        me.tableData[me.rowIndex][key] = val;
                                    };
                                };
                                me.tableData[me.rowIndex].remark = data.remark;
                                me.tableData[me.rowIndex].remarken = data.remarken;
                                me.tableData[me.rowIndex].defaultidlength = data.defaultidlength;
                                me.tableData[me.rowIndex].functionslong = data.functionslong;

                                me.$Message.success("编辑成功");
                            } else {
                                me.$Message.success("添加成功");
                                me.queryDevTypeList();
                            };
                            me.addDevTypeModal = false;
                        } else {
                            if (me.isEdit) {
                                if (resp.status == 1) {
                                    me.$Message.error("原设备类型不存在");
                                } else if (resp.status == 2) {
                                    me.$Message.error("新的设备类型重复");
                                }
                            } else {
                                me.$Message.error("操作失败");
                            };
                        }

                    })
                },
                openEditDevTypeModal: function(params) {
                    var row = params.row;
                    this.isEdit = true;
                    this.addDevTypeModal = true;
                    this.oldtypename = row.typename;
                    this.remark = row.remark;
                    this.remarken = row.remarken;
                    this.defaultidlength = row.defaultidlength;
                    this.devTypeInfo = JSON.parse(JSON.stringify(row));
                    this.rowIndex = params.index;
                    this.functionsCheck = this.setFunctionsLong(row.functionslong);
                },
                setFunctionsLong: function(functionslong) {

                    var functionsCheck = [];
                    var functionsDesc = this.functionsDesc;
                    for (var i = 0; i < functionsDesc.length; ++i) {
                        var desc = functionsDesc[i];
                        var mask = desc.mask;
                        if ((mask & functionslong) == mask) {
                            functionsCheck.push(mask);
                        }
                    }

                    return functionsCheck;
                },
                getFunctionsLong: function() {
                    var functionsLong = 0;
                    this.functionsCheck.forEach(function(mask) {
                        functionsLong = functionsLong | mask;
                    })
                    return functionsLong;
                },
                addInstructionsToDeviceTypes: function() {
                    var url = myUrls.editDeviceTypeCmd();
                    var data = this.getEditDeviceTypeCmdData();
                    var me = this;
                    utils.sendAjax(url, data, function(resp) {
                        if (resp.status == 0) {
                            me.$Message.success("设置成功");
                            me.cmdModal = false;
                            me.tableData[me.rowIndex].cmds = data.datas[0].cmds;
                            me.tableData[me.rowIndex].directiveCount = data.datas[0].cmds.length;
                        } else {
                            me.$Message.error(resp.cause);
                        }
                    })

                },
                getEditDeviceTypeCmdData: function() {
                    var cmdList = this.cmdList;
                    var selectedCmdObj = this.checkboxCmdObj;
                    var cmds = [];
                    for (var key in selectedCmdObj) {
                        if (selectedCmdObj.hasOwnProperty(key) && selectedCmdObj[key]) {
                            cmdList.forEach(function(children) {
                                children.forEach(function(item) {
                                    if (item.cmdcode == key) {
                                        cmds.push(item);
                                    };
                                })
                            })
                        };
                    };
                    return {
                        datas: [{
                            devicetype: this.tableData[this.rowIndex].devicetypeid,
                            cmds: cmds
                        }]
                    }
                },
                queryDevTypeList: function() {
                    var me = this;
                    var url = myUrls.queryDeviceTypeByUser();
                    utils.sendAjax(url, {}, function(resp) {
                        if (resp.status == 0) {
                            resp.devicetypes.forEach(function(item) {
                                if (item.cmds) {
                                    item.directiveCount = item.cmds.length;
                                } else {
                                    item.directiveCount = 0;
                                }
                            })

                            me.tableData = resp.devicetypes;

                        }
                    })
                },
                matchingCmd: function(deviceType) {
                    var me = this;
                    var index = 0;
                    me.checkboxCmdObj = {};
                    me.cmdList = [];
                    this.cmdRecords.forEach(function(item) {
                        if (item.devicetype == deviceType) {
                            var idx = parseFloat(index / 3)
                            if (index % 3 == 0) {
                                var newArr = [];
                                newArr.push(item)
                                me.cmdList.push(newArr);
                            } else {
                                me.cmdList[me.cmdList.length - 1].push(item);
                            }
                            me.checkboxCmdObj[item.cmdcode] = false;
                            index++;
                        }
                    });
                },
                querySelectedCmd: function() {
                    var url = myUrls.queryDeviceTypeHadCmd();
                    var data = {
                        "devicetype": this.tableData[this.rowIndex].devicetypeid
                    };
                    utils.sendAjax(url, data, this.doQuerySelectedCmdFn);
                },
                doQuerySelectedCmdFn: function(resp) {
                    var me = this;
                    if (resp.status == 0) {
                        this.tableData[me.rowIndex].cmds = resp.records;
                        for (var key in me.checkboxCmdObj) {
                            if (me.checkboxCmdObj.hasOwnProperty(key)) {
                                me.checkboxCmdObj[key] = false;
                            }
                        };

                        resp.records.forEach(function(item) {
                            me.checkboxCmdObj[item.cmdcode] = true;
                        });

                        this.tableData = JSON.parse(JSON.stringify(this.tableData));
                    }
                },
                queryCmdList: function() {
                    var me = this;
                    var url = myUrls.queryCmd();
                    var data = {
                        "offset": 0,
                        "pagesize": 100
                    };
                    utils.sendAjax(url, data, function(resp) {
                        if (resp.status === 0) {
                            var records = resp.records;
                            me.cmdRecords = records;
                        };
                    });

                },
                queryDeviceTypeCode: function() {
                    var me = this;
                    var url = myUrls.listDeviceTypeCode();
                    utils.sendAjax(url, {}, function(resp) {
                        if (resp.status === 0) {
                            resp.types.forEach(function(item) {
                                me.deviceTypeList.push({
                                    label: item,
                                    value: item
                                });
                            });
                        }
                    });
                },
                queryFunctionsDesc: function() {
                    var me = this;
                    var url = myUrls.queryFunctionsDesc();
                    utils.sendAjax(url, {}, function(respData) {
                        console.log('respData', respData);
                        me.functionsDesc = respData.records
                    })
                }
            },
            watch: {
                addDevTypeModal: function() {
                    if (!this.isEdit) {
                        this.devTypeInfo = {
                            "port": 0,
                            "typecode": null,
                            "typename": null,
                            "enable": 1,
                            "level": 0,
                            "camera": 0,
                            "lcd": 0,
                            "led": 0,
                            "phone": null,
                            "tcpport": 0,
                            "udpport": 0,
                        }
                        this.remark = "";
                        this.remarken = "";
                        this.defaultidlength = 11;
                        this.functionsCheck = [];
                    }
                }
            },
            mounted: function() {
                this.queryDevTypeList();
                this.queryCmdList();
                this.queryDeviceTypeCode();
                this.queryFunctionsDesc();
            }
        })
    </script>
</div>